#include "PrototypeThread.hpp"

boost::scoped_ptr<Mutex> PrototypeThread::m(new Mutex);
int PrototypeThread::tabValue[100] = {0};
int PrototypeThread::testValue = 0;
int PrototypeThread::i = 0;

class Increase1 : public ThreadJob
{
public:
    void * DoWork()
	{		
		value = 0;
		//try to get a share mutex integer
		do
		{
			value = PrototypeThread::getIncreaseValue(1);
            rest(1);
		} 
        while(value < 100);
		return (void*) value;
	}

    int value;
};

class Increase2 : public ThreadJob
{
public:
	void * DoWork()
	{
		value = 0;
		//try to get a share mutex integer
		do
		{
			value = PrototypeThread::getIncreaseValue(2);
            rest(1);
		}
        while(value < 100);
		return (void*)value;
	}

    int value;
};

int PrototypeThread::getIncreaseValue(int jobId)
{
	int tmp = 0;
	if(m->Lock())
	{	
		tabValue[testValue] = jobId;
		testValue++;
		tmp = testValue;
		m->UnLock();
	}
	return tmp;

}

void PrototypeThread::Run()
{

}

//////////////////////////////////////////////////////////////////////////
void PrototypeThread::Render(BITMAP* aBuffer)
{
    for (int i=0; i<100; ++i)
    {
        char text[64] = { '\0' };
        sprintf(text,"%.2i: job%i ",i, tabValue[i]);
        int col = i%25;
        int lin = (int)i/25;
        textout_ex(aBuffer, font, text, 10+(100*lin), 30+(col*10), (255,255,255), NULL);
    }
}

//////////////////////////////////////////////////////////////////////////
void PrototypeThread::Init()
{
	t1.reset( new Thread());
	t2.reset( new Thread());
	job1.reset(new Increase1());
	job2.reset(new Increase2());

	t1->Start(job1.get());
	t2->Start(job2.get());
	
}

//////////////////////////////////////////////////////////////////////////
void PrototypeThread::DeInit()
{   
	t1->Join();
	t2->Join();
	testValue = 0;
	i = 0;
	//memset(tabValue,0,10000002);

	t1.reset();
	t2.reset();
	job1.reset();
	job2.reset();
}